package de.gameduell.framework.util {

	/**
	 * Represents a Hashtable storing key-value pairs.
	 * You can get values by key or vice versa.
	 */
	public class HashMap {

		private var _keys:Array;
		private var _values:Array;

		/**
		 * Constructs new Hashtable;
		 */
		public function HashMap():void {
			_keys = new Array();
			_values = new Array();
		}		

		/**
		 * Maps the specified key to the specified value in this hashtable.
		 */	
		public function put(key:Object, value:Object):void {
			var index:int = _keys.indexOf(key);
			if( index == -1 ) {
				_keys.push(key);
				_values.push(value);	
			}
			else {
				_keys[index] = key;
				_values[index] = value;
			}
		}

		/**
		 * @return the value to which the specified key is mapped in this hashtable.
		 */
		public function get(key:Object):Object {
			var index:int = _keys.indexOf(key);
			if(index == -1) {
				return null;
			} else {
				return _values[index];
			}
		}

		/**
		 * getter method (with code completition for adobe flex develop).
		 **/
		public function getValue(key:Object):Object {
			return get(key);
		}
		
		/**
		 *  Removes the key (and its corresponding value) from this hashtable. 
		 */
		public function remove(key:Object):void {
			var keyIndex:int = _keys.indexOf(key);
			if(keyIndex != -1) {
				_keys.splice(keyIndex, 1);
				_values.splice(keyIndex, 1);	
			}
		}

		/**
		 * Clears this hashtable so that it contains no keys.
		 */
		public function clear():void {
			_keys = null;
			_values = null;
			_keys = new Array();
			_values = new Array();
		}

		/**
		 * Tests if the specified object is a key in this hashtable.
		 */
		public function containsKey(key:Object):Boolean {		
			return (_keys.indexOf(key) == -1) ? false : true;
		}

		/**
		 * Returns true if this Hashtable maps one or more keys to this value.
		 */
		public function containsValue(value:Object):Boolean {
			return (_values.indexOf(value) == -1) ? false : true;
		}

		/**
		 * Returns the number of keys in this hashtable.
		 */
		public function length():uint {
			return _keys.length;
		}

		/**
		 * Returns array of values
		 */
		public function get values():Array {
			return _values;
		}

		/**
		 * Returns array of keys
		 */
		public function get keys():Array {
			return _keys;
		}

		/**
		 * Returns a string representation of this Hashtable object
		 */
		public function toString():String {
			var string:String = "";
			for(var i:uint = 0;i < _keys.length; i++) {
				string += String(_keys[i]) + ":" + String(_values[i]) + " | ";
			} 
			return string;
		}

		/**
		 * Creates clone of map
		 */
		public function clone():HashMap {
			var clone:HashMap = new HashMap();
			for(var i:uint = 0;i < _keys.length; i++) {
				clone.put(_keys[i], _values[i]);
			}
			return clone;
		}
	}
}
